<?php

namespace App\Models;

use App\Http\Controllers\PdfController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * CompetiteActivityDatabase
 * Class ArticleModel
 * @package app\common\model
 */
class CompetiteActivityDatabase extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'competite_activity_database';




    /**
     * @param page int 当前页
     * @param limit int 分页大小
     * @param is_play int 是否发布 1 发布  2 未发布
     * @param keywords string 搜索关键词(作品数据库名称)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     */
    public function lists($field, $keywords, $is_play, $start_time, $end_time, $limit = null)
    {
        if (empty($field)) {
            $field = [
                'id', 'name', 'img', 'intro', 'is_play', 'create_time', 'browse_num'
            ];
        }
        $res = $this->select($field)->where(function ($query) use ($keywords) {
            $query->where('name', 'like', "%$keywords%");
        })->where(function ($query) use ($is_play, $start_time, $end_time) {
            if ($is_play) {
                $query->where('is_play', $is_play);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })
            ->where('is_del', 1)
            ->orderByDesc('sort')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     * 管理员详情
     * @param id 管理员id
     */
    public function detail($id, $field = null)
    {
        if (empty($field)) {
            $field = ['id', 'name', 'img', 'intro', 'is_play', 'create_time', 'browse_num'];
        }
        $res = $this->select($field)->where('is_del', 1)->where('id', $id)->first();

        return $res;
    }


    /**
     *  数据库作品统计
     */
    public function databaseWorksStatistics()
    {
        $res = $this->select('id', 'name')->where('is_del', 1)->orderByDesc('id')->paginate(999)->toArray();
        $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['works_number'] = $competiteActivityWorksDatabaseModel->databaseNumber($val['id']);
        }
        return $res;
    }

    /**
     *  数据库作品类型统计
     */
    public function databaseWorksTypeStatistics()
    {
        $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
        $works_number =  $competiteActivityWorksDatabaseModel->where('type', 1)->count();
        $ebook_number =  $competiteActivityWorksDatabaseModel->where('type', 2)->count();
        return [$works_number, $ebook_number];
    }
}
